﻿using Common.AspNetCore;
using Common.Infrastructure;
using Common.Infrastructure.Utils;
using Common.RunModels.File;
using File.Api.Models;
using File.Api.Service;
using File.Api.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace File.Api.Controllers
{
    [Route("api/Upload")]
    public class UploadController : ApiController
    {
        private readonly UploadFileService downloadFileService;
        private readonly IConfiguration configuration;

        public UploadController(IServiceProvider provider, UploadFileService auth, IConfiguration config)
             : base(provider)
        {
            this.downloadFileService = auth;
            this.configuration = config;
        }

        [HttpPost, Route("UpFile")]
        public async Task<ApiActionResult<UploadFileModel>> UpFile()
        {
            return await SafeExecuteAsync<UploadFileModel>(async (messages) =>
            {
                List<FileModel> files = new List<FileModel>();
                FileGroupModel filegroupModel = new FileGroupModel();
                UploadFileModel ret = new UploadFileModel(); 
                await GetUploadRequest(files, filegroupModel);
                if (files.Any())
                {
                    var st = await this.downloadFileService.UploadFilesAsync(files);
                    st?.ForEach(t =>
                    {
                        ret.Details.Add(new UploadFileDetailModel()
                        {
                            FileId = LibSysUtils.GrpcDeSerial(t.FileId),
                            FileName = LibSysUtils.GrpcDeSerial(t.FileName),
                        });
                    });
                }

                if (filegroupModel.Details.Any())
                {
                    var groupret = await this.downloadFileService.UploadFileGroupAsync(filegroupModel);
                    groupret.Details.ForEach(t =>
                    {
                        var s = new UploadFileDetailModel()
                        {
                            FileId = t.FileId,
                            FileGroupId = t.GroupId,
                            FileName = t.FileName,
                        };
                        if (t.Details != null)
                        {
                            t.Details.ForEach(t1 =>
                            {
                                s.Details.Add(new UploadFileDetailImgModel()
                                {
                                    FileId = t1.FileId,
                                    FileName = t1.FileName,
                                });
                            });
                        }

                        ret.Details.Add(s);
                    }); 
                } 

                return ret;
            });
        }

        [HttpPost, Route("UpFileByMenu")]
        public async Task<ApiActionResult<UploadFileModel>> UpFileByMenu([FromBody] FileModelByUserParamModel model)
        {
            return await SafeExecuteAsync<UploadFileModel>(async (messages) =>
            {
                List<FileModel> files = model.Files;
                FileGroupModel filegroupModel = new FileGroupModel();
                UploadFileModel ret = new UploadFileModel();
                if (files.Any())
                {
                    var st = await this.downloadFileService.UploadFilesAsync(files);
                    st?.ForEach(t =>
                    {
                        ret.Details.Add(new UploadFileDetailModel()
                        {
                            FileId = LibSysUtils.GrpcDeSerial(t.FileId),
                            FileName = LibSysUtils.GrpcDeSerial(t.FileName),
                        });
                    });
                }

                if (filegroupModel.Details.Any())
                {
                    var groupret = await this.downloadFileService.UploadFileGroupAsync(filegroupModel);
                    groupret.Details.ForEach(t =>
                    {
                        var s = new UploadFileDetailModel()
                        {
                            FileId = t.FileId,
                            FileGroupId = t.GroupId,
                            FileName = t.FileName,
                        };
                        if (t.Details != null)
                        {
                            t.Details.ForEach(t1 =>
                            {
                                s.Details.Add(new UploadFileDetailImgModel()
                                {
                                    FileId = t1.FileId,
                                    FileName = t1.FileName,
                                });
                            });
                        }

                        ret.Details.Add(s);
                    });
                }

                return ret;
            });
        }

        private async Task GetUploadRequest(List<FileModel> fileRequest, FileGroupModel updateFileGroupRequest)
        {
            var host = this.configuration["FrameworkApiUrl"];
            var httpRequest = HttpContext.Request;
            string url = host + "api/ImageConvert/ImageConvert";
            foreach (var key in httpRequest.Form.Files)
            {
                var postedFile = key;
                string fileName = postedFile.FileName;
                var pos = fileName.LastIndexOf(".");
                var extendName = fileName.Substring(pos);
                var inputStream = postedFile.OpenReadStream();
                bool isSuppot = FileUtils.Support(extendName);

                if (!string.IsNullOrEmpty(host) && isSuppot)
                {
                    ConvertImageFileParam param = new ConvertImageFileParam();
                    param.FileName = fileName;
                    byte[] fileData = new byte[(int)postedFile.Length];
                    Stream sr = inputStream;  ////创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    param.FileData = fileData;
                    var r = await WebApiUtils.PostAsync<MESJsonActionResult<ConvertImageFileParam>>(url, param);
                    if (!r.IsSuccessful)
                    {
                        this.AddWarning(r.ErrorMessage);
                    }

                    var imageFile = r?.Data;
                    var s = new FileGroupDetailModel()
                    {
                        FileName = fileName,
                        FileType = postedFile.ContentType,
                        FileData = fileData
                    };

                    if (imageFile != null && imageFile.Files != null && imageFile.Files.Any())
                    {
                        int index = 0;
                        imageFile.Files.ForEach(t =>
                        {
                            s.Details.Add(new FileGroupDetailFileModel()
                            {
                                FileName = t.FileName,
                                FileType = t.FileType,
                                FileData = t.FileData,
                                Index = index
                            });
                            index++;
                        });
                    }

                    updateFileGroupRequest.Details.Add(s);
                }
                else
                {
                    byte[] fileData = new byte[(int)postedFile.Length];
                    Stream sr = inputStream;  ////创建数据流对象 
                    sr.Read(fileData, 0, (int)postedFile.Length);
                    fileRequest.Add(new FileModel()
                    {
                        FileData = fileData,
                        FileName = fileName,
                        FileType = postedFile.ContentType
                    });
                }
            }
        }
    }
}
